const { pool } = require('../config/db');
const { success, error } = require('../utils/response');
const moment = require('moment');
const { sendRenewApprovedNotice } = require('./notificationController');

// ===== 用户端 =====

// 提交续借申请
exports.submitRenewApplication = async (req, res, next) => {
  try {
    const { borrowRecordId } = req.body;
    const userId = req.userId;

    // 获取借阅记录
    const [records] = await pool.query(`
      SELECT
        br.*,
        b.name as book_name,
        b.id as book_id,
        u.user_type,
        brl.max_renew_times
      FROM borrow_records br
      LEFT JOIN books b ON br.book_id = b.id
      LEFT JOIN users u ON br.user_id = u.id
      LEFT JOIN borrow_rules brl ON brl.user_type = u.user_type
      WHERE br.id = ? AND br.user_id = ? AND br.status = 'borrowed'
    `, [borrowRecordId, userId]);

    if (records.length === 0) {
      return error(res, '借阅记录不存在或无法续借', 404);
    }

    const record = records[0];
    const maxRenewTimes = record.max_renew_times || 2;

    // 检查续借次数
    if (record.renew_count >= maxRenewTimes) {
      return error(res, `最多只能续借${maxRenewTimes}次`, 400);
    }

    // 检查是否已有待审批的续借申请
    const [existingApps] = await pool.query(
      'SELECT id FROM renew_applications WHERE borrow_record_id = ? AND status = "pending"',
      [borrowRecordId]
    );

    if (existingApps.length > 0) {
      return error(res, '已有待审批的续借申请，请勿重复提交', 400);
    }

    // 检查是否有预约
    const [reservations] = await pool.query(
      'SELECT COUNT(*) as count FROM reservations WHERE book_id = ? AND status = "waiting"',
      [record.book_id]
    );

    if (reservations[0].count > 0) {
      return error(res, '此书已被预约，无法续借', 400);
    }

    // 计算续借天数
    const renewDays = record.borrow_days || 30;

    // 创建续借申请
    const [result] = await pool.query(`
      INSERT INTO renew_applications 
      (borrow_record_id, user_id, book_id, renew_days)
      VALUES (?, ?, ?, ?)
    `, [borrowRecordId, userId, record.book_id, renewDays]);

    success(res, {
      applicationId: result.insertId,
      bookName: record.book_name,
      renewDays: renewDays,
      status: 'pending'
    }, '续借申请提交成功，请等待管理员审核');

  } catch (err) {
    next(err);
  }
};

// 获取用户的续借申请记录
exports.getUserRenewApplications = async (req, res, next) => {
  try {
    const userId = req.userId;
    const { status } = req.query; // pending, approved, rejected

    let whereClause = 'WHERE ra.user_id = ?';
    let params = [userId];

    if (status) {
      whereClause += ' AND ra.status = ?';
      params.push(status);
    }

    const [applications] = await pool.query(`
      SELECT
        ra.id,
        ra.apply_time,
        ra.status,
        ra.approve_time,
        ra.reject_reason,
        ra.renew_days,
        b.id as book_id,
        b.name as book_name,
        b.author,
        b.cover,
        br.due_date as current_due_date,
        br.renew_count
      FROM renew_applications ra
      LEFT JOIN books b ON ra.book_id = b.id
      LEFT JOIN borrow_records br ON ra.borrow_record_id = br.id
      ${whereClause}
      ORDER BY ra.apply_time DESC
    `, params);

    success(res, applications);
  } catch (err) {
    next(err);
  }
};

// 取消续借申请
exports.cancelRenewApplication = async (req, res, next) => {
  try {
    const { id } = req.params;
    const userId = req.userId;

    // 检查申请是否存在且状态为待审批
    const [applications] = await pool.query(
      'SELECT * FROM renew_applications WHERE id = ? AND user_id = ? AND status = "pending"',
      [id, userId]
    );

    if (applications.length === 0) {
      return error(res, '续借申请不存在或无法取消', 404);
    }

    // 删除申请
    await pool.query('DELETE FROM renew_applications WHERE id = ?', [id]);

    success(res, { id }, '续借申请已取消');
  } catch (err) {
    next(err);
  }
};

// ===== 管理员端 =====

// 获取所有续借申请（管理员）
exports.getAllRenewApplications = async (req, res, next) => {
  try {
    const { page = 1, limit = 10, status, keyword } = req.query;
    const offset = (page - 1) * limit;

    let whereClause = 'WHERE 1=1';
    let params = [];

    if (status) {
      whereClause += ' AND ra.status = ?';
      params.push(status);
    }

    if (keyword) {
      whereClause += ' AND (b.name LIKE ? OR u.username LIKE ? OR u.phone LIKE ?)';
      params.push(`%${keyword}%`, `%${keyword}%`, `%${keyword}%`);
    }

    const [applications] = await pool.query(`
      SELECT
        ra.id,
        ra.apply_time,
        ra.status,
        ra.approve_time,
        ra.reject_reason,
        ra.renew_days,
        u.id as user_id,
        u.username,
        u.phone,
        u.user_type,
        b.id as book_id,
        b.name as book_name,
        b.author,
        br.borrow_date,
        br.due_date as current_due_date,
        br.renew_count,
        brl.max_renew_times,
        au.username as approver_name
      FROM renew_applications ra
      LEFT JOIN users u ON ra.user_id = u.id
      LEFT JOIN books b ON ra.book_id = b.id
      LEFT JOIN borrow_records br ON ra.borrow_record_id = br.id
      LEFT JOIN borrow_rules brl ON brl.user_type = u.user_type
      LEFT JOIN admin_users au ON ra.approve_by = au.id
      ${whereClause}
      ORDER BY ra.apply_time DESC
      LIMIT ? OFFSET ?
    `, [...params, parseInt(limit), offset]);

    const [total] = await pool.query(`
      SELECT COUNT(*) as count 
      FROM renew_applications ra
      LEFT JOIN books b ON ra.book_id = b.id
      LEFT JOIN users u ON ra.user_id = u.id
      ${whereClause}
    `, params);

    success(res, {
      applications,
      pagination: {
        current: parseInt(page),
        limit: parseInt(limit),
        total: total[0].count,
        pages: Math.ceil(total[0].count / limit)
      }
    });
  } catch (err) {
    next(err);
  }
};

// 批准续借申请（管理员）
exports.approveRenewApplication = async (req, res, next) => {
  const connection = await pool.getConnection();
  
  try {
    const { id } = req.params;
    const adminId = req.userId;

    await connection.beginTransaction();

    // 获取续借申请详情
    const [applications] = await connection.query(`
      SELECT
        ra.*,
        br.due_date as current_due_date,
        b.name as book_name
      FROM renew_applications ra
      LEFT JOIN borrow_records br ON ra.borrow_record_id = br.id
      LEFT JOIN books b ON ra.book_id = b.id
      WHERE ra.id = ? AND ra.status = 'pending'
    `, [id]);

    if (applications.length === 0) {
      await connection.rollback();
      return error(res, '续借申请不存在或已处理', 404);
    }

    const application = applications[0];

    // 计算新的到期日期
    const newDueDate = moment(application.current_due_date)
      .add(application.renew_days, 'days')
      .format('YYYY-MM-DD HH:mm:ss');

    // 更新借阅记录
    await connection.query(
      'UPDATE borrow_records SET due_date = ?, renew_count = renew_count + 1 WHERE id = ?',
      [newDueDate, application.borrow_record_id]
    );

    // 更新续借申请状态
    await connection.query(
      'UPDATE renew_applications SET status = "approved", approve_time = NOW(), approve_by = ? WHERE id = ?',
      [adminId, id]
    );

    await connection.commit();

    // 发送通知
    sendRenewApprovedNotice(id, application.user_id, application.book_name, true);

    success(res, {
      id,
      newDueDate,
      renewDays: application.renew_days
    }, '续借申请已批准');

  } catch (err) {
    await connection.rollback();
    next(err);
  } finally {
    connection.release();
  }
};

// 拒绝续借申请（管理员）
exports.rejectRenewApplication = async (req, res, next) => {
  try {
    const { id } = req.params;
    const { rejectReason } = req.body;
    const adminId = req.userId;

    // 检查申请是否存在且状态为待审批
    const [applications] = await pool.query(`
      SELECT ra.*, b.name as book_name
      FROM renew_applications ra
      LEFT JOIN books b ON ra.book_id = b.id
      WHERE ra.id = ? AND ra.status = 'pending'
    `, [id]);

    if (applications.length === 0) {
      return error(res, '续借申请不存在或已处理', 404);
    }

    const application = applications[0];

    // 更新续借申请状态
    await pool.query(
      'UPDATE renew_applications SET status = "rejected", approve_time = NOW(), approve_by = ?, reject_reason = ? WHERE id = ?',
      [adminId, rejectReason || '不符合续借条件', id]
    );

    // 发送通知
    sendRenewApprovedNotice(id, application.user_id, application.book_name, false);

    success(res, { id, rejectReason }, '续借申请已拒绝');
  } catch (err) {
    next(err);
  }
};

// 获取续借申请统计（管理员）
exports.getRenewApplicationStats = async (req, res, next) => {
  try {
    const [stats] = await pool.query(`
      SELECT
        COUNT(*) as total_count,
        SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending_count,
        SUM(CASE WHEN status = 'approved' THEN 1 ELSE 0 END) as approved_count,
        SUM(CASE WHEN status = 'rejected' THEN 1 ELSE 0 END) as rejected_count
      FROM renew_applications
    `);

    success(res, stats[0]);
  } catch (err) {
    next(err);
  }
};

